import { jwtDecode } from "jwt-decode";
import { defineStore } from "pinia";

interface JwtPayload {
    id: number,
    nick: string,
    username: string,
}

export const useUserStore = defineStore('userStore', {
    state: () => ({
        id: 0,
        nick: '',
        username: '',
        avatar: '',
        qq: '',
        token: '',
    }),
    actions: {
        set(token: string) {
            this.token = token;
            //解析jwt并赋值
            const data = jwtDecode<JwtPayload>(token);
            this.id = data.id;
            this.nick = data.nick;
            this.username = data.username;
        }, init() {
            const token = sessionStorage.getItem("token") as string;
            if (token) {
                this.set(token);
            }
        }
    }
})


const userStore = useUserStore();
userStore.init();